﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;
using com.lover.astd.common.manager;

namespace com.lover.astd.common.partner.impl
{
    public class _91Login : LoginImplBase
    {
        public _91Login() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            byte[] bytes = Encoding.UTF8.GetBytes(_acc.Password);
            int byte_length = bytes.Length;
            byte[] final_bytes = new byte[byte_length + 15];
            bytes.CopyTo(final_bytes, 0);
            final_bytes[byte_length] = 0xa3;
            final_bytes[byte_length + 1] = 0xac;
            final_bytes[byte_length + 2] = 0xa1;
            final_bytes[byte_length + 3] = 0xa3;
            byte[] suffix_bytes = Encoding.UTF8.GetBytes("fdjf,jkgfkl");
            suffix_bytes.CopyTo(final_bytes, byte_length + 4);
            string enc = CommonUtils.generateBytesMd5(final_bytes);
            string md5_password = enc.ToLower();

            string loginurl = String.Format("https://aq.91.com/AjaxAction/AC_userlogin.ashx?CallBack=jsonp{0}&siteflag=221&nduseraction=login&txtUserName={1}&txtPassword={2}&checkcode=",
                TimeMgr.TimeStamp, _username, md5_password);
            HttpResult resp = TransferMgr.doGetPure(loginurl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string retstr = resp.getContent(Encoding.GetEncoding("GBK"));

            if (!retstr.Contains("登陆成功"))
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            string redirecturl = String.Format("http://web.91.com/AS/LoginGame.ashx?ServerID={0}&Channel=2&LoginBack=http://as.91.com/", _acc.ServerId);
            resp = TransferMgr.doGetPure(redirecturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetServerList; return result; }

            //<script language="javascript" type="text/javascript">window.location.href="...";</script>
            string content = resp.getContent();
            Regex re = new Regex("href=\"([^\"']*?)\"");
            Match m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            string gameurl = m.Groups[1].Value;

            processStartGame(gameurl, result, ref cookies);
            return result;
        }
    }
}
